package org.budo.support.lang.util;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author lmw
 */
public class SetUtil {
    public static <T> T firstOrNull(Set<T> set) {
        if (null == set || set.size() < 1) {
            return null;
        }

        return set.iterator().next();
    }

    public static <T> Set<T> toSet(Collection<T> collection) {
        if (null == collection) {
            return null;
        }

        Set<T> set = new HashSet<T>();
        set.addAll(collection);
        return set;
    }

    public static <T> Set<T> toSet(T... array) {
        if (null == array) {
            return null;
        }

        Set<T> set = new HashSet<T>();
        for (T each : array) {
            if (null != each) {
                set.add(each);
            }
        }
        return set;
    }

    /**
     * 判断集合是否包含指定元素, 集合为空时返回false, 指定元素为空时返回 falseS
     */
    public static <T> Boolean contains(Set<T> set, T value) {
        return null != set && null != value && set.contains(value);
    }

    public static Boolean isEmpty(Collection<?> set) {
        return null == set || set.isEmpty();
    }

    public static Boolean containsAny(Set<?> setA, Set<?> setB) {
        if (isEmpty(setA) || isEmpty(setB)) {
            return false;
        }

        for (Object each : setA) {
            if (setB.contains(each)) {
                return true;
            }
        }

        return false;
    }

    public static Boolean hasIntersection(Collection<?> a, Collection<?> b) {
        if (isEmpty(a) || isEmpty(b)) {
            return false;
        }

        Set setA = asSet(a);
        for (Object each : b) {
            if (setA.contains(each)) {
                return true;
            }
        }

        return false;
    }

    private static <T> Set<T> asSet(Collection<T> collection) {
        if (null == collection) {
            return null;
        }

        if (collection instanceof Set) {
            return (Set<T>) collection;
        }

        return toSet(collection);
    }
}